package com.mo.tools.core;

import org.springframework.beans.BeanUtils;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description: SpringBeanUtil
 * version: v.1.0
 *
 * @date: 2019/09/04 14:31
 * @author: YangXingfu
 */
public abstract class SpringBeanUtil {

    /**
     * 对象拷贝
     * @param source 源对象
     * @param target 目标对象
     * @param <T> 泛型类型
     */
    public static <T> void copy (@NonNull T source, @NonNull T target) {

        if (source == null) {
            target = null;
            return ;
        }
        Assert.notNull(target, "target model not initialize");
        BeanUtils.copyProperties(source, target);
    }

    /**
     * 对象拷贝
     * @param source 源对象
     * @param targetClass 目标对象类型
     * @param <T> 泛型类型
     * @return 目标对象
     */
    public static <T> T copy(@NonNull Object source, @NonNull Class<T> targetClass) {
        if (source == null) {
            return null;
        }
        Assert.notNull(targetClass, "target model Class in null");
        T target = null;
        try {
            target = targetClass.newInstance();
            BeanUtils.copyProperties(source, target);

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return target;
    }

    /**
     * 对象集合拷贝
     * @param sources 源对象集合
     * @param targetClass 目标对象集合类型
     * @param <T> 泛型类型
     * @return 目标对象集合
     */
    public static <T> List<T> copyList(@NonNull Collection<?> sources, @NonNull Class<T> targetClass) {
        if (sources == null) {
            return null;
        }
        return sources.stream().map(source -> copy(source, targetClass)).collect(Collectors.toList());
    }
}
